package sk.ogame.realm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sk.ogame.brain.Memory;
import sk.ogame.brain.thing.BuildingThing;
import sk.ogame.brain.thing.Thing;
import sk.ogame.brain.thing.ThingService;
import sk.ogame.entity.Building;
import sk.ogame.entity.Planet;
import sk.ogame.realm.exception.BaseException;
import sk.ogame.realm.exception.NotSupportThingException;
import sk.ogame.realm.exception.ResourceNotEnoughException;
import java.util.List;

/**
 * @author 支绍昆
 * 2023/2/15
 **/
@Service
public class BuildingService implements ThingService {

    @Autowired
    private Memory memory;
    @Autowired
    private PlanetService planetService;
    @Autowired
    private ClientHttpService clientHttpService;

    @Override
    public Thing dealThing(Thing thing) {
        if (thing instanceof BuildingThing) {
            BuildingThing buildingThing = (BuildingThing) thing;
            switch (buildingThing.getOperate()) {
                case leveUp:
                    levelUp(buildingThing.getPlanetId(), buildingThing.getBuildId());
                    return null;
                default:
                    throw new NotSupportThingException(null, 0);
            }
        }
        throw new NotSupportThingException(null, 0);
    }

    //获取建筑详情
    public List<Building> detail(int planetId) {
        if (!planetService.isCurrent(planetId)) {
            planetService.change(planetId);
        }
        return clientHttpService.planetBuildDetail();
    }

    //建筑升级
    public void levelUp(int planetId, int buildId) {
        Planet planet = memory.getPlanetInPeriod(planetId);

        //获取升级等级需要资源。
        List<Building> list = detail(planetId);
        Building detail = findBuilding(list, buildId);
        int metalGap = detail.getMetal() - planet.getMetal();
        int crystalGap = detail.getCrystal() - planet.getCrystal();
        int deuteriumGap = detail.getDeuterium() - planet.getDeuterium();

        //判断资源是否足够。
        if (metalGap > 0 || crystalGap > 0 || deuteriumGap > 0) {
            ResourceNotEnoughException notEnough = new ResourceNotEnoughException("build resource not enough", 0);
            notEnough.setPlanetId(planetId);
            notEnough.setNeedMetal(Math.max(metalGap, 0));
            notEnough.setNeedCrystal(Math.max(crystalGap, 0));
            notEnough.setNeedDeuterium(Math.max(deuteriumGap, 0));
            throw notEnough;
        }

        clientHttpService.planetBuildUp(buildId);
    }

    //------------------------------- private ----------------------------------

    private Building findBuilding(List<Building> list, int buildId) {
        for (Building building : list) {
            if (buildId == building.getBid()) {
                return building;
            }
        }
        throw new BaseException("can not find the building : " + buildId, 0);
    }
}
